package logger

import (
	"io"
	"os"
	"time"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"

	"pool/pool_backend/config"
)

var Logger *zap.Logger
var Sugar *zap.SugaredLogger

// InitLogger 初始化日志
func InitLogger(cfg *config.LoggerConfig) error {
	// 日志级别
	level := getLogLevel(cfg.Level)
	
	// 日志编码器
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	// 设置日志输出
	var writer io.Writer
	if cfg.Output == "file" {
		writer = &lumberjack.Logger{
			Filename:   cfg.FilePath,
			MaxSize:    100, // MB
			MaxBackups: 10,
			MaxAge:     30, // days
			Compress:   true,
		}
	} else {
		writer = os.Stdout
	}

	// 设置日志格式
	var encoder zapcore.Encoder
	if cfg.Format == "json" {
		encoder = zapcore.NewJSONEncoder(encoderConfig)
	} else {
		encoder = zapcore.NewConsoleEncoder(encoderConfig)
	}

	// 创建Core
	core := zapcore.NewCore(
		encoder,
		zapcore.AddSync(writer),
		level,
	)

	// 创建Logger
	Logger = zap.New(
		core,
		zap.AddCaller(),
		zap.AddCallerSkip(1),
		zap.AddStacktrace(zapcore.ErrorLevel),
	)

	// 创建Sugar Logger
	Sugar = Logger.Sugar()

	// 替换全局Logger
	zap.ReplaceGlobals(Logger)

	Info("Logger initialized successfully")
	return nil
}

// getLogLevel 获取日志级别
func getLogLevel(levelStr string) zapcore.Level {
	switch levelStr {
	case "debug":
		return zapcore.DebugLevel
	case "info":
		return zapcore.InfoLevel
	case "warn":
		return zapcore.WarnLevel
	case "error":
		return zapcore.ErrorLevel
	default:
		return zapcore.InfoLevel
	}
}

// Debug 记录debug级别日志
func Debug(msg string, fields ...zap.Field) {
	Logger.Debug(msg, fields...)
}

// Info 记录info级别日志
func Info(msg string, fields ...zap.Field) {
	Logger.Info(msg, fields...)
}

// Warn 记录warn级别日志
func Warn(msg string, fields ...zap.Field) {
	Logger.Warn(msg, fields...)
}

// Error 记录error级别日志
func Error(msg string, fields ...zap.Field) {
	Logger.Error(msg, fields...)
}

// Fatal 记录fatal级别日志并退出
func Fatal(msg string, fields ...zap.Field) {
	Logger.Fatal(msg, fields...)
}

// DebugF 格式化记录debug级别日志
func DebugF(template string, args ...interface{}) {
	Sugar.Debugf(template, args...)
}

// InfoF 格式化记录info级别日志
func InfoF(template string, args ...interface{}) {
	Sugar.Infof(template, args...)
}

// WarnF 格式化记录warn级别日志
func WarnF(template string, args ...interface{}) {
	Sugar.Warnf(template, args...)
}

// ErrorF 格式化记录error级别日志
func ErrorF(template string, args ...interface{}) {
	Sugar.Errorf(template, args...)
}

// FatalF 格式化记录fatal级别日志并退出
func FatalF(template string, args ...interface{}) {
	Sugar.Fatalf(template, args...)
}

// WithFields 创建带有字段的Logger
func WithFields(fields map[string]interface{}) *zap.Logger {
	zapFields := make([]zap.Field, 0, len(fields))
	for k, v := range fields {
		zapFields = append(zapFields, zap.Any(k, v))
	}
	return Logger.With(zapFields...)
}

// Sync 同步日志
func Sync() {
	_ = Logger.Sync()
}

// Now 返回格式化的当前时间
func Now() string {
	return time.Now().Format("2006-01-02 15:04:05")
} 